<?php
class PapiWS_UserimageController extends Ext_Controller_ServerAction
{
	protected $_serverClass = 'PapiWS_Service_UserImage';
	protected $_aliasClass = 'UserImage';
	protected $_classMap = array(
		'PapiWS_Model_UserImageVO'	=> 'cl.dimacofionline.pe.vo.viewport.UserImageVO',
		'PapiWS_Model_ShapeVO'      => 'cl.dimacofionline.pe.vo.viewport.ShapeVO',
	);


	//
	// Metodos usados para uploadear files.
	//
	public function uploadformAction() {
		$this->render();
	}

	public function uploadAction() {
		// test for token
		$token = trim($this->getRequest()->getParam('token'));
		if ( $token === null )
			throw new Exception( 'Debe especificar el token de sesión.' );

		// hagamos el upload
		$uploadPath = $this->getUploadPath($token);
		$maxFileSize = Zend_Registry::get('config')->dirs->image_upload->maxSize;

		$form = new Zend_Form();
		$element = new Zend_Form_Element_File('uploadedfile');

        // ensure only 1 file
        $element->addValidator('Count', false, 1);

        // limit to 100K
		if (isset($maxFileSize)) {
        	$element->addValidator('Size', false, $maxFileSize);
		}

        // only JPEG, PNG, and GIFs
        $element->addValidator('Extension', false, 'jpg,png');
        $form->addElement( $element );	

		// lo mandamos a algo q no me vaya a traer problemas
		$imageName = md5(uniqid());
		$newName = $this->buildImageFilePath( $uploadPath, $imageName );
		$form->uploadedfile->addFilter( 'Rename', array('source' => "*",
			'target' => $newName,
			'overwrite' => true 
		));

		// Creo el registro para obetener el id.
		$isValid = $form->isValid( $this->getRequest()->getParams() );
		if ( ! $isValid ) {
			$errorMsg = implode( "\n", $form->uploadedfile->getMessages() );
			throw new Exception( 'Error haciendo el upload. Error: ' . $errorMsg . '.');
		}

		// recibimos el file
		if ( ! $form->uploadedfile->receive() ) {
			throw new Exception( 'Error haciendo el upload.' );
		}


		// como solo soportamos un file a la vez debería devolver
		// el path de ESE file

		// lo guardamos en Zend_Cache con toda la info
		$imageVo = $this->buildImageVO( $token, $imageName );

		$cacheId = 'userimage_' . $token;
		$imageList = Zend_Registry::get('userImageCache')->load( $cacheId );
		if ( ! $imageList ) {
			$imageList = array();
		}

		$imageList[$imageName] = $imageVo;

		Zend_Registry::get('userImageCache')->save( $imageList, $cacheId );
		return $imageList;
	}
	
	public function viewAction() {

		// test for token
		$token = trim($this->getRequest()->getParam('token'));
		$inCache = true;

		if ( $token === '' ) {
			// test for product id
			$personalizedProductId = (int) trim($this->getRequest()->getParam('personalizedProductId'));
			if ( $personalizedProductId === 0 ) {
				throw new Exception( 'Debe especificar el token de sesión o el id de producto.' );
			}
			$inCache = false;
		}

		$id = trim($this->getRequest()->getParam('id'));
		if ( $id === '' )
			throw new Exception( 'Debe especificar el id dela imagen.' );

		$showThumb = $this->getRequest()->getParam('action') == 'thumb';
		if ( $inCache ) {
			$this->showImageFromCache( $token, $id, $showThumb );
		} else {
			$this->showImageFromStorage( $personalizedProductId, $id, $showThumb );
		}
		return;
	}

	public function thumbAction() {
		// uso el mismo código que viewAction();
		$this->viewAction();
	}

	private function showImageFromCache( $token, $id, $thumb = false )
	{
		// levantar info del cache.
		$cacheId = 'userimage_' . $token;
		$imageList = Zend_Registry::get('userImageCache')->load( $cacheId );
		if ( $imageList == null || ! isset($imageList[$id])) {
			// buscamos la imagen en el filesystem porque no está en el cache.
			$imageVo = $this->buildImageVO( $token, $id );
			if ( $imageVo === null ) {
				throw new Exception( 'Image not found!' );
			}
		} else {
			$imageVo = $imageList[$id];
		}
		$imagePath = $this->buildImageFilePath( $this->getUploadPath( $token ), $imageVo->id );

		if ( $thumb ) {
			$thumbPath = $imagePath . '.thumb';
			if ( ! file_exists( $thumbPath ) ) {
				// generamos 
				$width = Zend_Registry::get('config')->dirs->image_upload->thumbnailWidth;
				$cmd = "convert $imagePath -resize ${width}x${width} $thumbPath";
				system($cmd);
			}
			$imagePath = $thumbPath;
		}
		header( 'Content-type: ' . $imageVo->mime );
		$fp = fopen($imagePath, "rb");
		fpassthru($fp);
		exit(0);
	}

	private function showImageFromStorage( $personalizedProductId, $id, $thumb = false )
	{

		$uiservice = new PapiWS_Service_UserImage();
		$imagePath = $uiservice->getImagePath( $personalizedProductId, $id );
		if ( $thumb ) {
			$thumbPath = $imagePath . '.thumb';
			if ( ! file_exists( $thumbPath ) ) {
				// generamos 
				$width = Zend_Registry::get('config')->dirs->image_upload->thumbnailWidth;
				$cmd = "convert $imagePath -resize ${width}x${width} $thumbPath";
				system($cmd);
			}
			$imagePath = $thumbPath;
		}
		$imageInfo = getimagesize( $imagePath );
		header( 'Content-type: ' . $imageInfo['mime'] );
		$fp = fopen($imagePath, "rb");
		fpassthru($fp);
		exit(0);
	}
	
	// rebuild ImageVO from image info
	private function buildImageVO( $token, $id ) {
		$uploadPath = $this->getUploadPath( $token );
		$filename = $this->buildImageFilePath( $uploadPath, $id );

		if ( ! file_exists( $filename ) ) {
			return null;
		}

		$imageProps = getimagesize( $filename );

        $imageUrl = sprintf( "%s/id/%s/token/%s",
            Zend_Registry::get('config')->image_storage->imageUrl,
            $id,
            $token
        );
        $thumbUrl= sprintf( "%s/id/%s/token/%s",
            Zend_Registry::get('config')->image_storage->thumbUrl,
            $id,
            $token
        );

		$imageVo = new PapiWS_Model_UserImageVO();
		$imageVo->imageUrl 		= $imageUrl;
		$imageVo->thumbnailUrl 	= $thumbUrl;
		$imageVo->mime      	= $imageProps['mime'];
		$imageVo->size      	= filesize($filePath);
		$imageVo->width	 		= $imageProps[0];
		$imageVo->height		= $imageProps[1];
		$imageVo->id			= $id;

		return $imageVo;
	}

	// get uploadPath and create dir if it doesn't exist
	private function getUploadPath($token) {
		$uploadPath = Zend_Registry::get('config')->dirs->image_upload->path;
		$uploadPath .= DIRECTORY_SEPARATOR . $token;

		if ( ! file_exists($uploadPath) ) {
			mkdir( $uploadPath );
		}
		return $uploadPath;
	}

	// build image path
	private function buildImageFilePath( $uploadPath, $imageName ) {
		return $uploadPath . DIRECTORY_SEPARATOR . $imageName;
	}
}
